﻿package com.bluediesel.utils.managers.scenemanager.commands {
	import flash.events.Event;
	
	public class ParallelCommand extends TimedCommand {
		
		private var _commands:Array = [];
		
		public function ParallelCommand(delay:Number, ...commands) {
			//trace ("COMMANDS: " + commands);
			for each (var cmd:Object in commands){
				//trace (cmd + " is a new parallel command");
				this._commands.push(cmd);
			}
			super(delay);
			//trace ("New Parallel command");
		}
		
		override public function executeAll():void {
			execute();
		}
		
		private var _completeCommandCount:int;
		
		override final protected function execute(obj:Object = null):void {
			
			//set the complete command count to zero
			_completeCommandCount = 0;
			
			for each (var command:Command in _commands) {
				
				//listen for the complete event of a subcommand...
				command.addEventListener(Event.COMPLETE, onSubcommandComplete);
				
				//...and start the subcommand
				//trace ("SSSSSStarting parallel command " + command);
				command.start();
			}
		}
		
		private function onSubcommandComplete(e:Event):void {
			
			//stop listening for the complete event
			Command(e.target).removeEventListener(Event.COMPLETE, onSubcommandComplete);
			
			//increment the complete command count
			_completeCommandCount++;

			//if all the commands are complete...
			if (_completeCommandCount == _commands.length) {
				//trace ("PARALLEL COMMAND COMPLETE " + this);
				//...then this parallel command is complete
				complete();
			}
			//else trace ("THAT WAS NOT THE LAST SUBCOMMAND OF THE PARALLEL SUBCOMMANDS " + _completeCommandCount + " of " + _commands.length);
		}
	}
}